/**
 * 状态管理
 */
import { createPinia, PiniaPluginContext } from 'pinia'
import { getStorage, setStorage } from '../utils'
import { storePrefixKeyName } from '../config'
import { toRaw } from 'vue'

type PiniaPluginOptions = {
  key: string
}

// 使用本地存储保存pinia的状态
const piniaPlugin = (options: PiniaPluginOptions) => {
  return (context: PiniaPluginContext) => {
    const { store } = context
    const data = getStorage(`${options?.key ?? storePrefixKeyName}-${store.$id}`)
    store.$subscribe(() => {
      setStorage(`${options?.key ?? storePrefixKeyName}-${store.$id}`, toRaw(store.$state))
    })
    return {
      ...data
    }
  }
}

const store = createPinia()
store.use(piniaPlugin({
  key: storePrefixKeyName
}))

export default store